from data_type import *
#from framework.capture__ import *
from scapy import *
import datetime
import pickle
def sqlInjectDetection():
    '''
    sqlInjectDetection:
        args: None(But need to run it after capture and get pkl file)
        return: 
            sql_att: list(tuple(index, time, keyword, srcip))
            sql_att_log: str(sql_att)
    '''
    flowForSqlI = []
    
    ###########################从pkl文件中获取flowForSqlI列表###########################
    Ethernet = EthernetPkt()
    Ipv4 = Ipv4Pkt()
    Ipv6 = Ipv6Pkt()
    Tcp = TcpPkt()
    Udp = UdpPkt()
    Arp = ArpPkt()
    Dns = DnsPkt()
    Icmpv4 = Icmpv4Pkt()
    Icmpv6 = Icmpv6Pkt()
    HttpReq = HttpReqPkt()
    HttpRes = HttpResPkt()
    
    eachPkt = Packet(Ethernet, Ipv4, Ipv6, Tcp, Udp, Arp, Dns, Icmpv4, Icmpv6, HttpReq, HttpRes)
        
    #with open("C://Users//leslie//Desktop//res//cur//demo.pkl",'rb') as f:
    with open("attack_demo//demo.pkl",'rb') as f:
    #with open("sniffRes//cur//demo.pkl",'rb') as f:
        while 1:
            try:
                eachPkt = pickle.load(f)
                flowForSqlI.append(eachPkt)
                # print(eachPkt)
                # eachPkt.PrintFlag()
            except EOFError:
                break
    ###########################从pkl文件中获取flowForSqlI列表###########################
    sql_att = []
    index = 0
    for pkt in flowForSqlI:
        # print(pkt.flag)
        index += 1
        if pkt.IsHttpReq():
            pkt = pkt.GetHttpReq()
            # print(pkt)
            # pkt.PrintMyInfo()
            Path_str = pkt.GetField("path")
            # print(Path_str)
            with open('sql.txt', 'r+') as file:
                for line in file.readlines():
                    if line.strip('\n') in Path_str:
                        # print("An sql injection attack was identified:")
                        # print("\tTime:", str(datetime.datetime.now()))
                        # print("\tKey Word:", line.strip('\n'))
                        # print("\tAtt source:", pkt.GetField("host"))
                        sql_att.append((index, datetime.datetime.now(), line.strip('\n'), pkt.GetField("host")))
        else:
            if pkt.IsTcp():
                tcp = pkt.GetTcp()
                if pkt.IsIpv4():
                    ipv4 = pkt.GetIpv4()
                else:
                    continue
                # print(tcp)
                # tcp.PrintMyInfo()
                Packet_str = tcp.GetField("raw")
                # print(Packet_str)
                with open('sql.txt', 'r+') as file:
                    for line in file.readlines():
                        if line.strip('\n') in Packet_str:
                            # beiattack = re.findall('Host: \w{3}\.\w{3}\.\w{3}\.\w{3}', str(Packet_str))
                            # print("An sql injection attack was identified:")
                            # print("\tTime:", str(datetime.datetime.now()))
                            # print("\tKey Word:", line.strip('\n'))
                            sql_att.append((index, datetime.datetime.now(), line.strip('\n'), ipv4.GetField("srcIp")))
                            # print("\tAtt source:", beiattack[0].strip("Host: "))
    sql_att_log = ["packetID:"+str(i) + "\ttime:"+str(a) + "\tKeyWord:"+str(b) + "\tSrcIp:"+str(c) for i, a, b, c in sql_att]
    return sql_att, sql_att_log

if __name__ == "__main__":
    for x in sqlInjectDetection()[1]:
        print(x)
